package com.example.springdatajpaderivedquerymethod.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springdatajpaderivedquerymethod.model.People;
import com.example.springdatajpaderivedquerymethod.repositories.PeopleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/people")
public class PeopleController {

    @Autowired
    private PeopleRepository peopleRepository;

    @PostMapping(value = "/saveAll",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Void> saveAll(@RequestBody List<People> peoples){
        peopleRepository.saveAll(peoples);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping(value = "/moveToHistory",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Boolean> moveToHistory(@RequestParam("peopleId") final Integer peopleId){
        Boolean isMoveSuccess = peopleRepository.movePersonToHistory(peopleId);
        return new ResponseEntity<>(isMoveSuccess,HttpStatus.OK);
    }

    @GetMapping(value = "/fetchPeopleLimit",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<People>> fetchPeopleLimit(@RequestParam("limit") final Integer limit){
        List<People> peoples = peopleRepository.fetchPeopleLimit(limit);
        return new ResponseEntity<>(peoples,HttpStatus.OK);
    }

    @GetMapping(value = "/findDuplicatedObjects",produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<List<String>> findDuplicatedObjects(){
        List<String> list = Arrays.asList("A", "B", "B", "C", "D", "D", "Z", "E", "E");
        List<String> results = list.stream()
                .collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
                .entrySet()
                .stream()
                .filter(e -> e.getValue() > 1l)
                .map(e -> e.getKey())
                .collect(Collectors.toList());
        return new ResponseEntity<>(results,HttpStatus.OK);
    }
}
